package com.zhoug.common.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


import com.zhoug.common.prodivers.AppContextProvider;
import com.zhoug.common.utils.LogUtils;

import androidx.lifecycle.LiveData;

/**
 * 网络监听LiveData
 * 注意静态的LiveData在应用退出时需要注销(设为null),否则再次进入应用可以会收到上次的数据(app进程没被系统回收时)
 * @Author 35574
 * @Date 2020/4/29
 * @Description
 */
public class NetworkLiveData extends LiveData<NetworkInfo> {
    private static final String TAG = ">>>NetworkLiveData";
    private NetWorkReceiver mNetWorkReceiver;
    private IntentFilter mIntentFilter;
    private static NetworkLiveData instance;


    private NetworkLiveData() {
        mIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mNetWorkReceiver = new NetWorkReceiver();
    }

    public static NetworkLiveData getInstance() {
        if (instance == null) {
            synchronized (NetworkLiveData.class) {
                if (instance == null) {
                    instance = new NetworkLiveData();
                }
            }
        }
        return instance;
    }

    public static void destroy(){
        if(instance!=null){
            instance.mIntentFilter=null;
            instance.mNetWorkReceiver=null;
            instance=null;
        }
    }


    @Override
    protected void onActive() {
        super.onActive();
        LogUtils.d(TAG, "onActive:注册网络监听");
        AppContextProvider.getAppContext().registerReceiver(mNetWorkReceiver, mIntentFilter);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        LogUtils.d(TAG, "onInactive:注销网络监听");
        AppContextProvider.getAppContext().unregisterReceiver(mNetWorkReceiver);

    }

    private static class NetWorkReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
                NetworkLiveData.getInstance().postValue(activeNetwork);
            }


        }
    }

}

